package com.example.service.impl;

import com.example.entity.Permission;
import com.example.entity.Role;
import com.example.entity.RolePermission;
import com.example.entity.UserRole;
import com.example.mapper.PermissionMapper;
import com.example.mapper.RoleMapper;
import com.example.mapper.RolePermissionMapper;
import com.example.mapper.UserRoleMapper;
import com.example.service.PermissionInitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 权限初始化服务实现
 */
@Service
public class PermissionInitServiceImpl implements PermissionInitService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Override
    @Transactional
    public void initializeBasicPermissions() {
        // 创建基础权限
        createPermissionIfNotExists("user:profile:view", "查看个人信息", "OPERATION", 0L, "查看用户个人信息权限");
        createPermissionIfNotExists("user:profile:edit", "编辑个人信息", "OPERATION", 0L, "编辑用户个人信息权限");
        createPermissionIfNotExists("user:password:change", "修改密码", "OPERATION", 0L, "修改用户密码权限");
        
        // 创建头像相关权限
        createPermissionIfNotExists("user:avatar:upload", "上传头像", "OPERATION", 0L, "用户上传头像权限");
        createPermissionIfNotExists("user:avatar:update", "更新头像", "OPERATION", 0L, "用户更新头像权限");
        createPermissionIfNotExists("user:avatar:delete", "删除头像", "OPERATION", 0L, "用户删除头像权限");
        
        // 创建基础角色
        createRoleIfNotExists("USER", "普通用户", "系统普通用户角色");
        createRoleIfNotExists("STORE_MANAGER", "店长", "店长角色，可以管理排班和预约");
        
        // 为普通用户角色分配基础权限
        assignBasicPermissionsToUserRole();
        
        // 为店长角色分配权限
        assignPermissionsToStoreManagerRole();
    }
    
    @Override
    @Transactional
    public void createBasicUserPermissions(Long userId) {
        // 检查用户是否已有角色
        List<UserRole> userRoles = userRoleMapper.selectByUserId(userId);
        
        if (userRoles.isEmpty()) {
            // 为新用户分配普通用户角色
            Role userRole = roleMapper.selectByRoleCode("USER");
            if (userRole != null) {
                UserRole newUserRole = new UserRole();
                newUserRole.setUserId(userId);
                newUserRole.setRoleId(userRole.getId());
                newUserRole.setCreateTime(LocalDateTime.now());
                newUserRole.setDeleted(0);
                userRoleMapper.insert(newUserRole);
            }
        }
    }
    
    @Override
    public void checkAndCreateMissingPermissions() {
        // 只检查和创建最基础的权限，不创建角色
        createPermissionIfNotExists("user:profile:view", "查看个人信息", "OPERATION", 0L, "查看用户个人信息权限");
        createPermissionIfNotExists("user:profile:edit", "编辑个人信息", "OPERATION", 0L, "编辑用户个人信息权限");
        createPermissionIfNotExists("user:password:change", "修改密码", "OPERATION", 0L, "修改用户密码权限");

        // 检查头像相关权限
        createPermissionIfNotExists("user:avatar:upload", "上传头像", "OPERATION", 0L, "用户上传头像权限");
        createPermissionIfNotExists("user:avatar:update", "更新头像", "OPERATION", 0L, "用户更新头像权限");
        createPermissionIfNotExists("user:avatar:delete", "删除头像", "OPERATION", 0L, "用户删除头像权限");

        // 检查通知管理相关权限
        createPermissionIfNotExists("notice:list", "查看通知列表", "OPERATION", 0L, "查看通知公告列表权限");
        createPermissionIfNotExists("notice:view", "查看通知详情", "OPERATION", 0L, "查看通知公告详情权限");
        createPermissionIfNotExists("notice:add", "添加通知", "OPERATION", 0L, "添加通知公告权限");
        createPermissionIfNotExists("notice:update", "编辑通知", "OPERATION", 0L, "编辑通知公告权限");
        createPermissionIfNotExists("notice:delete", "删除通知", "OPERATION", 0L, "删除通知公告权限");
        createPermissionIfNotExists("notice:publish", "发布通知", "OPERATION", 0L, "发布通知公告权限");
        
        // 检查排班管理相关权限
        createPermissionIfNotExists("store:schedule:view", "查看排班", "OPERATION", 0L, "查看店长排班权限");
        createPermissionIfNotExists("store:schedule:add", "添加排班", "OPERATION", 0L, "添加店长排班权限");
        createPermissionIfNotExists("store:schedule:update", "编辑排班", "OPERATION", 0L, "编辑店长排班权限");
        createPermissionIfNotExists("store:schedule:delete", "删除排班", "OPERATION", 0L, "删除店长排班权限");
        
        // 检查用户查看排班权限
        createPermissionIfNotExists("user:schedule:view", "查看店长排班", "OPERATION", 0L, "用户查看店长排班权限");
        
        // 检查预约相关权限
        createPermissionIfNotExists("user:appointment:view", "查看预约", "OPERATION", 0L, "用户查看预约权限");
        createPermissionIfNotExists("user:appointment:create", "创建预约", "OPERATION", 0L, "用户创建预约权限");
        createPermissionIfNotExists("user:appointment:cancel", "取消预约", "OPERATION", 0L, "用户取消预约权限");
        createPermissionIfNotExists("store:appointment:view", "查看店长预约", "OPERATION", 0L, "店长查看预约权限");
        createPermissionIfNotExists("store:appointment:cancel", "店长取消预约", "OPERATION", 0L, "店长取消预约权限");
        createPermissionIfNotExists("store:appointment:complete", "完成预约", "OPERATION", 0L, "店长完成预约权限");
        createPermissionIfNotExists("admin:appointment:view", "管理员查看预约", "OPERATION", 0L, "管理员查看所有预约权限");
        createPermissionIfNotExists("admin:appointment:confirm", "确认预约", "OPERATION", 0L, "管理员确认预约权限");

        // 检查购买相关权限
        createPermissionIfNotExists("user:purchase:buy", "购买商品", "OPERATION", 0L, "用户购买商品权限");
        createPermissionIfNotExists("user:purchase:view", "查看购买记录", "OPERATION", 0L, "用户查看购买记录权限");
        createPermissionIfNotExists("user:purchase:cancel", "取消购买记录", "OPERATION", 0L, "用户取消购买记录权限");

        // 检查消费记录相关权限
        createPermissionIfNotExists("user:consumption:view", "查看消费记录", "OPERATION", 0L, "用户查看消费记录权限");
        createPermissionIfNotExists("store:income:view", "查看收入记录", "OPERATION", 0L, "店长查看收入记录权限");

        // 检查余额相关权限
        createPermissionIfNotExists("user:balance:view", "查看余额", "OPERATION", 0L, "用户查看余额权限");
        createPermissionIfNotExists("user:recharge", "用户充值", "OPERATION", 0L, "用户充值权限");
        createPermissionIfNotExists("user:recharge:records", "查看充值记录", "OPERATION", 0L, "用户查看充值记录权限");
    }
    
    /**
     * 创建权限（如果不存在）
     */
    private void createPermissionIfNotExists(String permissionCode, String permissionName, 
                                           String permissionType, Long parentId, String description) {
        Permission existingPermission = permissionMapper.selectByCode(permissionCode);
        if (existingPermission == null) {
            Permission permission = new Permission();
            permission.setPermissionCode(permissionCode);
            permission.setPermissionName(permissionName);
            permission.setPermissionType(permissionType);
            permission.setParentId(parentId);
            permission.setDescription(description);
            permission.setSort(0);
            permission.setStatus(1);
            permission.setCreateTime(LocalDateTime.now());
            permission.setUpdateTime(LocalDateTime.now());
            permission.setDeleted(0);
            
            permissionMapper.insert(permission);
        }
    }
    
    /**
     * 创建角色（如果不存在）
     */
    private void createRoleIfNotExists(String roleCode, String roleName, String description) {
        Role existingRole = roleMapper.selectByRoleCode(roleCode);
        if (existingRole == null) {
            Role role = new Role();
            role.setRoleCode(roleCode);
            role.setRoleName(roleName);
            role.setDescription(description);
            role.setStatus(1);
            role.setCreateTime(LocalDateTime.now());
            role.setUpdateTime(LocalDateTime.now());
            role.setDeleted(0);
            
            roleMapper.insert(role);
        }
    }
    
    /**
     * 为普通用户角色分配基础权限
     */
    private void assignBasicPermissionsToUserRole() {
        Role userRole = roleMapper.selectByRoleCode("USER");
        if (userRole == null) {
            return;
        }
        
        // 基础权限编码列表
        List<String> basicPermissionCodes = Arrays.asList(
            "user:profile:view",
            "user:profile:edit",
            "user:password:change",
            "user:avatar:upload",
            "user:avatar:update", 
            "user:avatar:delete",
            "user:schedule:view",
            "user:appointment:view",
            "user:appointment:create",
            "user:appointment:cancel",
            "notice:list",
            "notice:view",
            "user:purchase:buy",
            "user:purchase:view",
            "user:purchase:cancel",
            "user:consumption:view",
            "user:balance:view",
            "user:recharge",
            "user:recharge:records"
        );
        
        assignPermissionsToRole(userRole.getId(), basicPermissionCodes);
    }
    
    /**
     * 为店长角色分配权限
     */
    private void assignPermissionsToStoreManagerRole() {
        Role storeManagerRole = roleMapper.selectByRoleCode("STORE_MANAGER");
        if (storeManagerRole == null) {
            return;
        }
        
        // 店长权限编码列表（包含用户基础权限 + 店长专有权限）
        List<String> storeManagerPermissionCodes = Arrays.asList(
            "user:profile:view",
            "user:profile:edit",
            "user:password:change",
            "user:avatar:upload",
            "user:avatar:update", 
            "user:avatar:delete",
            "user:schedule:view",
            "user:appointment:view",
            "user:appointment:create",
            "user:appointment:cancel",
            "notice:list",
            "notice:view",
            "user:purchase:buy",
            "user:purchase:view",
            "user:purchase:cancel",
            "user:consumption:view",
            "user:balance:view",
            "user:recharge",
            "user:recharge:records",
            "store:schedule:view",
            "store:schedule:add",
            "store:schedule:update",
            "store:schedule:delete",
            "store:appointment:view",
            "store:appointment:cancel",
            "store:appointment:complete",
            "store:income:view"
        );
        
        assignPermissionsToRole(storeManagerRole.getId(), storeManagerPermissionCodes);
    }
    
    /**
     * 为角色分配权限的通用方法
     */
    private void assignPermissionsToRole(Long roleId, List<String> permissionCodes) {
        for (String permissionCode : permissionCodes) {
            Permission permission = permissionMapper.selectByCode(permissionCode);
            if (permission != null) {
                // 检查角色权限关联是否已存在
                List<RolePermission> existingRolePermissions = rolePermissionMapper.selectByRoleId(roleId);
                boolean hasPermission = existingRolePermissions.stream()
                    .anyMatch(rp -> rp.getPermissionId().equals(permission.getId()));
                
                if (!hasPermission) {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(permission.getId());
                    rolePermission.setCreateTime(LocalDateTime.now());
                    rolePermission.setDeleted(0);
                    rolePermissionMapper.insert(rolePermission);
                }
            }
        }
    }
}
